<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                :label="item.cate_name"
                :value="item.id"
                v-for="item in ArtCateList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArticleList()"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="resetForm"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="pubDialogVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="ArticleList" border style="width: 100%">
        <el-table-column prop="title" label="文章标题">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDetail(row.id)">{{
              row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="文章分类"> </el-table-column>
        <el-table-column prop="pub_date" label="发布时间">
          <template v-slot="{ row }">
            {{ formatData(row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="deleteArticle(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        style="margin-top: 15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 文章详情页的对话框 start -->
    <el-dialog
      title="提示"
      :visible.sync="detailVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span
        ><!-- 查看文章详情的对话框 -->
        <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
          <h1 class="title">{{ artDetail.title }}</h1>

          <div class="info">
            <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
            <span>发布时间：{{ formatData(artDetail.pub_date) }}</span>
            <span>所属分类：{{ artDetail.cate_name }}</span>
            <span>状态：{{ artDetail.state }}</span>
          </div>

          <!-- 分割线 -->
          <el-divider></el-divider>

          <img
            :src="
              'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img
            "
            alt=""
          />

          <div v-html="artDetail.content"></div> </el-dialog
      ></span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">取 消</el-button>
        <el-button type="primary" @click="detailVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 文章详情页的对话框 end -->

    <!-- 发布文章的对话框start -->
    <el-dialog
      title="发布文章"
      :visible.sync="pubDialogVisible"
      fullscreen
      :before-close="handleClose"
      @closed="closeResetForm"
    >
      <!-- 发布文章的对话框 -->
      <el-form
        :model="pubForm"
        :rules="pubFormRules"
        ref="pubFormRef"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            v-model="pubForm.cate_id"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in ArtCateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 文章内容 -->
        <el-form-item label="文章内容" prop="content">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <!-- 文章封面 -->
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img
            src="../../../assets/images/cover.jpg"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="onChangeFile"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <el-button type="primary" @click="pubArticle('已发布')"
          >发布文章</el-button
        >
        <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
      </el-form>
    </el-dialog>
    <!-- 发布文章的对话框end -->
  </div>
</template>

<script>
import defaultImg from '@/assets/images/cover.jpg'
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data() {
    return {
      // 保存详情页的数据
      artDetail: {},
      // detailVisible 控制详情页对话框显示和隐藏
      detailVisible: false,
      // 存储文章总的条数
      total: 0,
      // 查询参数对象
      // pagenum 获取第几页的数据
      // pagesize 控制每一页的条数
      //cate_id 获取指定分类的数据,实现数据过滤
      // state
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 控制发布文章对话框的显示和隐藏
      pubDialogVisible: false,
      // 表单的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        // 用户选择的封面图片(null表示没有选择任何封面)
        cover_img: null,
        state: '' // 值只能是 "已发布" || "草稿"
      },
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '文章标题的长度为1-100个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      // 保存文章分类
      ArtCateList: [],
      // 保存文章列表的数据
      ArticleList: []
    }
  },
  created() {
    // 获取文章的分类列表
    this.getArtCateList()
    // 获取文章列表的数据
    this.getArticleList()
  },
  methods: {
    // 删除文章
    deleteArticle(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 确定删除
          const { data: res } = await this.$http.delete('/my/article/info', {
            params: { id }
          })
          if (res.code !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          if (this.ArticleList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          //重新获取数据
          this.getArticleList()
        })
        .catch(() => {})
    },
    async showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', {
        params: {
          id
        }
      })
      if (res.code === 0) {
        this.artDetail = res.data
        this.detailVisible = true
      }
    },
    // 重置表单
    resetForm() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.getArticleList()
    },
    // 切换每一页显示多少条时触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 默认调到第一页
      this.q.pagenum = 1
      this.q.pagesize = val
      this.getArticleList()
    },
    //切换当前页码时触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.getArticleList()
    },
    //格式化时间的函数
    formatData(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取文章列表的数据
    async getArticleList() {
      // 发送请求获取数据
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      if (res.code === 0) {
        this.total = res.total
        this.ArticleList = res.data
      }
    },
    //重置表单
    closeResetForm() {
      this.$refs.pubFormRef.resetFields()
      this.pubForm.cover_img = null
      this.$refs.imgRef.setAttribute('src', defaultImg)
      this.pubForm.state = ''
    },
    // 发布文章
    pubArticle(state) {
      // 1.绑定事件函数
      this.pubForm.state = state
      // 2.表单校验
      this.$refs.pubFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('文章信息不完整')
        if (this.pubForm.cover_img === null) {
          return this.$message.error('请上传封面')
        }
        // FormData 格式 : 网络传输数据放入一种格式
        const fd = new FormData()
        // 高级写法
        Object.keys(this.pubForm).forEach((key) => {
          //console.log(key,'OK');
          console.log(this.pubForm[key], 'OK')
          fd.append(key, this.pubForm[key])
        })
        //3.发送请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 4.关闭对话框
        this.pubDialogVisible = false
        // 清空input type = file 的值
        this.$refs.iptFile.value = ''
        // 5.重新获取列表的数据
        this.getArticleList()
      })
    },
    onChangeFile(e) {
      // 获取用户选择的文件列表  e.target.files
      const fileList = e.target.files
      if (fileList.length > 0) {
        // 用户选择了封面
        this.pubForm.cover_img = fileList[0]
        // URL.createObjectURL 将文件对象转化为图片地址  将图片对象 存储程序的内存中 返回一个地址
        const url = URL.createObjectURL(fileList[0])
        // 设置图片的src属性
        this.$refs.imgRef.setAttribute('src', url)
      } else {
        // 用户没有选择封面
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', defaultImg)
      }
    },
    /* chooseImg() {
      // 模拟文件选择器的点击事件
      this.$refs.iptFile.click()
    }, */
    // 获取文章分类的数据
    async getArtCateList() {
      //发送请求获取数据
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code === 0) {
        this.ArtCateList = res.data
      }
    },
    handleClose(done) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // done() 可以关闭
          done()
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
